﻿using FictionsDownload.DAL;
using Zzw;
using FictionsDownload.Model;
using FictionsDownload.Static;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace FictionsDownload.BLL
{
    class UrlComparer : IComparer<string>
    {
        private int GetInt(char[] value,ref int index)
        {
            string reString = "";
            while(index < value.Length)
            {
                reString += value[index++].ToString();
                if (reString.IsNoInt())
                {
                    reString = reString.Substring(0, reString.Length - 1);
                    index--;
                    break;
                }
            }
            return int.Parse(reString);
        }
        private string GetString(char[] value, ref int index)
        {
            string reString = "";
            while (index < value.Length)
            {
                char c = value[index++];
                if (c.IsInt())
                {
                    index--;
                    break;
                }
                else
                {
                    reString += c;
                }
            }
            return reString;
        }
        public int Compare(string first, string second)
        {
            int returnCompare = first.Length.CompareTo(second.Length);
            if(returnCompare != 0)
            {
                return returnCompare;
            }
            else
            {
                return first.CompareTo(second);
            }
        }
    }
    public class Book:BaseBLL
    {
        public void Delete(BookModel book)
        {
            book.Delete(dal);
        }
        public bool Update(BookModel bookModel)
        {
            //Book数据校验
            if (bookModel.Name == "" || bookModel.Name == null)
            {
                Message = "名称为空";
                return false;
            }
            if (bookModel.Url == "" || bookModel.Url == null)
            {
                Message = "Url为空";
                return false;
            }
            Message = "更新成功";
            bookModel.ActiveTime = DateTime.Now;
            dal.Update(bookModel);
            return true;
        }

        public bool Add(BookModel bookModel)
        {
            //Book数据校验
            if (bookModel.Name == "" || bookModel.Name == null)
            {
                Message = "名称为空";
                return false;
            }
            if (bookModel.Url == "" || bookModel.Url == null)
            {
                Message = "Url为空";
                return false;
            }
            //数据库重复查询
            if (Get<BookModel>(b=>b.Url == bookModel.Url) == null)
            {
                if (Get<BookModel>(b=>b.Name == bookModel.Name) == null)
                {
                    dal.Insert(bookModel);
                    Message = "添加成功";
                    return true;
                }
                else
                {
                    Message = "已有名称";
                    return false;
                }
            }
            else
            {
                Message = "已有URL";
                return false;
            }
        }
        /// <summary>
        /// 下载目录页，取出章节键值对（Url:章节名）
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, string> ToDirectorys(BookModel book)
        {
            //提取Html
            string downloadUrl = book.DirectoryUrl ?? book.Url;
            string html = HttpHelper.DownloadHtml(downloadUrl);
            if (html == null)
            {
                return null;
            }
            string bodyHtml = HtmlHelper.HtmlTrim(html, book.HtmlHead, book.HtmlTail);
            //提取下载链接
            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
            Regex reg = new Regex("<a (style.{0,30})?href ?=\".*?((/|http)?.*?)\".*?>(.*?)</a>");
            Match match;
            while (true)
            {
                match = reg.Match(bodyHtml);
                if (match.Success)
                {
                    if (!keyValuePairs.ContainsKey(match.Groups[2].Value))
                    {
                        keyValuePairs.Add(match.Groups[2].Value, match.Groups[4].Value);
                    }
                }
                else
                {
                    break;
                }
                bodyHtml = bodyHtml.Substring(match.Index + match.Length);
            }
            //排序
            if(book.SortOrder == System.Windows.Forms.SortOrder.Ascending)
            {
                keyValuePairs = keyValuePairs.OrderBy(m=>m.Key,
                    new UrlComparer()
                    ).ToDictionary(k => k.Key, v => v.Value);
            }
            else if(book.SortOrder == System.Windows.Forms.SortOrder.Descending)
            {
                keyValuePairs = keyValuePairs.OrderByDescending(m => m.Key,
                    new UrlComparer()
                    ).ToDictionary(k => k.Key, v => v.Value);
            }
            else if(book.SortOrder == System.Windows.Forms.SortOrder.None)
            {
                //不做处理
            }
            return keyValuePairs;
        }
    }
}
